import router from "@/router";
import { useUserStoreHook } from "@/store/modules/user";
import { usePermissionStoreHook } from "@/store/modules/permission";
import { useDictStoreHook } from "@/store/modules/dictionary";

import NProgress from "nprogress";
import "nprogress/nprogress.css";

import { useRoute } from "vue-router";

const dashboard = () => import("@/views/dashboardWindows/index.vue");
NProgress.configure({ showSpinner: false }); // 进度条

const permissionStore = usePermissionStoreHook();

const useDictStore = useDictStoreHook();

const WORKBENCH = import.meta.env.VITE_APP_WORKBENCH;

const route = useRoute();

// 白名单路由
const whiteList = [
  "/login",
  "/scanningCode",
  "/common-table",
  "/custom-table",
  "/complex-table",
  "/drag-table",
  "/iframePrint",
  "/iframePrintCombine",
  "/iframePrintUnpack",
  "/iframePrintUnit",
  "/iframePrintDelivery",
  "/iframePrintReturn",
  "/iframePrintReturnDelivery",
  "/iframePrintSrmDelivery",
  "/iframePrintDeliveryUnit",
  "/iframePrintSrmDeliveryUnit",
  "/iframePrintUnitOne",
  "/iframePrintReturnUnitOne",
  "/dataScreen/mes",
  "/dataScreen/jt",
  "/demo/srmPurchaseDemand",
  "/dataScreen/JTSmeltScreen",
];

const userStore = useUserStoreHook();

// router.options.routes[3].children[0].component = dashboard;
// console.log("router.beforeEach", router.options.routes);
router.beforeEach(async (to, from, next) => {
  NProgress.start();
  const hasToken = userStore.token;
  if (hasToken) {
    //自定义帆软图表名称
    if (to.name === "CustomFineReport" && to.query?.viewlet) {
      to.meta.title = to.query?.viewlet;
    }
    if (to.path === "/login") {
      // 如果已登录，跳转工作台
      next({ path: "/" });
      NProgress.done();
    } else {
      const hasRoles = permissionStore.routes?.length;
      if (hasRoles) {
        // 未匹配到任何路由，跳转404
        if (to.matched.length === 0) {
          // alert(from.name);
          from.name ? next({ name: from.name }) : next("/404");
        } else {
          next();
        }
      } else {
        try {
          if (whiteList.indexOf(to.path) !== -1) {
            next();
          } else if (!hasRoles) {
            // 重新获取用户信息
            await userStore.getInfo();
            // 重新获取权限按钮
            await userStore.getButtonPermission();
            // 重新获取路由权限
            const accessRoutes = await permissionStore.generateRoutes();
            accessRoutes.forEach((route) => {
              router.addRoute(route);
            });
            // 重新获取字典数据集合
            await useDictStore.getDictionaryList();
            next({ ...to, replace: true });
            setTimeout(async () => {
              await userStore.getUnReadMessage();
            }, 1000);
          } else {
            next({ ...to, replace: true });
          }
        } catch (error) {
          // 移除 token 并跳转登录页
          await userStore.resetStore();
          next(`/login?redirect=${to.fullPath}`);
          NProgress.done();
        }
      }
    }
  } else {
    // 未登录可以访问白名单页面
    if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      next(`/login?redirect=${to.fullPath}`);
      NProgress.done();
    }
  }
});

router.afterEach(() => {
  NProgress.done();
});
